import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:hi_net/core/hi_net_adapter.dart';
import 'package:hi_net/request/hi_base_request.dart';
import 'package:path/path.dart';

/// Dio适配器
class DioAdapter extends HiNetAdapter {
  final dio = Dio();

  // DioAdapter() {
  //   dio.httpClientAdapter = IOHttpClientAdapter()
  //     ..onHttpClientCreate = (HttpClient client) {
  //       client.findProxy = (uri) {
  //         return 'PROXY 192.168.18.23:8888;DIRECT;';
  //       };
  //       client.badCertificateCallback =
  //           (X509Certificate cert, String host, int port) => true;
  //       return client;
  //     };
  // }

  @override
  Future<HiNetResponse<T>> send<T>(HiBaseRequest request) async {
    Response? response;
    var options = Options(headers: request.headers);
    DioError? error;
    try {
      if (request.httpMethod() == HttpMethod.GET) {
        response = await dio.get(
          request.url(),
          options: options,
          queryParameters: request.params,
        );
      } else if (request.httpMethod() == HttpMethod.POST) {
        response = await dio.post(
          request.url(),
          options: options,
          data: request.params,
        );
      } else if (request.httpMethod() == HttpMethod.UploadPost) {
        List<String> filePaths = request.params['file'];
        List<MultipartFile> files = [];
        await Future.forEach(filePaths, (element) async {
          var bytes = await compressImage(element);
          if (bytes != null) {
            files.add(MultipartFile.fromBytes(
              bytes,
              filename: basename(element),
            ));
          }
        });
        var queryParameters = request.params;
        queryParameters.remove('file');

        final formData = FormData.fromMap({'file': files});

        response = await dio.post(
          request.url(),
          options: options,
          queryParameters: queryParameters,
          data: formData,
        );
      }
    } on DioError catch (e) {
      error = e;
      response = e.response;
    }
    if (error != null) {
      // 抛出HiNetError
      throw HiNetError(response?.statusCode ?? -1, error.toString(),
          data: await buildRes(response, request));
    }
    return buildRes(response, request);
  }

  /// 构建HiNetResponse
  Future<HiNetResponse<T>> buildRes<T>(
      Response? response, HiBaseRequest request) {
    return Future.value(
      HiNetResponse(
        data: response?.data,
        request: request,
        statusCode: response?.statusCode,
        statusMessage: response?.statusMessage,
        extra: response,
      ),
    );
  }

  Future<Uint8List?> compressImage(String path) async {
    var result = await FlutterImageCompress.compressWithFile(
      path,
      quality: 85,
    );
    return result;
  }
}
